package com.hboxs.asl.wechat.utils;

import com.hboxs.asl.wechat.WechatConfig;
import com.hboxs.asl.wechat.message.respone.*;
import com.hboxs.asl.wechat.payment.base.WxPayException;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息工具类
 */
public final class WxXmlUtil {

    private static final Logger logger = Logger.getLogger(WxXmlUtil.class);

    /**
     * 返回消息类型：文本
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";

    /**
     * 返回消息类型：音乐
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

    /**
     * 返回消息类型：图文
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";

    /**
     * 返回消息类型：图片
     */
    public static final String RESP_MESSAGE_TYPE_IMAGE = "image";

    /**
     * 请求消息类型：文本
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";

    /**
     * 请求消息类型：图片
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

    /**
     * 请求消息类型：链接
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";

    /**
     * 请求消息类型：地理位置
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

    /**
     * 请求消息类型：音频
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

    /**
     * 请求消息类型：推送
     */
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";

    /**
     * 事件类型：subscribe(订阅)
     */
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

    /**
     * 事件类型：unsubscribe(取消订阅)
     */
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

    /**
     * 事件类型：CLICK(自定义菜单点击事件)
     */
    public static final String EVENT_TYPE_CLICK = "CLICK";

    /**
     * 二维码
     */
    public static final String EVENT_KEY_CLICK_QRCODE = "QRCODE";
    /**
     * 合伙人招募
     */
    public static final String EVENT_KEY_CLICK_PARTNER_RECRUIT = "PARTNER_RECRUIT";
    /**
     * 联盟商家入驻
     */
    public static final String EVENT_KEY_CLICK_RECRUITMENT = "RECRUITMENT";
    /**
     * A币e币使用说明
     */
    public static final String EVENT_KEY_CLICK_AECOIN = "AECOIN";
    /**
     * 区域运营中心
     */
    public static final String EVENT_KEY_CLICK_OPERATION_CENTER = "OPERATION_CENTER";
    /**
     * 错误消息
     */
    public static final String EVENT_KEY_CLICK_ERROR = "ERROR";

    /**
     * 事件类型：地理位置上报
     */
    public static final String EVENT_TYPE_LOCATION = "LOCATION";

    /**
     * 事件类型：扫描二维码
     */
    public static final String EVENT_TYPE_SCAN = "SCAN";

    /**
     * 事件类型：跳转链接
     */
    public static final String EVENT_TYPE_VIEW = "VIEW";

    /**
     * 事件类型：关于EASIN
     */
    public static final String EVENT_TYPE_ABOUT = "ABOUT_EASIN";

    /**
     * 事件类型：加入EASIN
     */
    public static final String EVENT_TYPE_JOIN = "JOIN_EASIN";
    /**
     * 解析微信发来的请求（XML）
     *
     * @param request 微信请求
     * @return xml结果
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(HttpServletRequest request) throws WxPayException {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<>();
        InputStream inputStream = null;

        try {
            // 从request中取得输入流
            inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();

            Document document = reader.read(inputStream);

            String xml = document.asXML();

            logger.info("Before Decrypt:" + xml);

            String msgSignature = request.getParameter("msg_signature");
            String timeStamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");

            // 解密
            xml = decryptXml(msgSignature, timeStamp, nonce, xml);

            logger.info("After Decrypt:" + xml);

            // 读取解密后的xml
            document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));

            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();

            // 遍历所有子节点
            for (Element e : elementList)
                map.put(e.getName(), e.getText());
        } catch (Exception e) {
            throw new WxPayException(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    // 释放资源
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }

        return map;
    }

    /**
     * 解密微信发来的消息（XML）
     *
     * @param msgSignature 消息签名
     * @param timeStamp    时间戳
     * @param nonce        随机字符串
     * @param encryptXml   加密xml
     * @return 解密xml
     */
    @SuppressWarnings("unchecked")
    public static String decryptXml(String msgSignature, String timeStamp, String nonce, String encryptXml) throws Exception {

        String xml = null;

        // 解密
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(
                WechatConfig.TOKEN,
                WechatConfig.ENCODING_AES_KEY,
                WechatConfig.APP_ID
        );

        try {
            xml = wxBizMsgCrypt.decryptMsg(msgSignature, timeStamp, nonce, encryptXml);
//            System.out.println("解密后："+xml);
        } catch (AesException e) {
            e.printStackTrace();
        }

        return xml;
    }

    /**
     * 文本消息对象转换成xml
     *
     * @param textMessage 文本消息对象
     * @return xml
     */
    public static String textMessageToXml(TextMessage textMessage) {
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }

    /**
     * 音乐消息对象转换成xml
     *
     * @param musicMessage 音乐消息对象
     * @return xml
     */
    public static String musicMessageToXml(MusicMessage musicMessage) {
        xstream.alias("xml", musicMessage.getClass());
        return xstream.toXML(musicMessage);
    }

    /**
     * 图片消息对象转换成xml
     *
     * @param imageMessage 图片消息对象
     * @return xml
     */
    public static String imageMessageToXml(ImageMessage imageMessage) {
        xstream.alias("xml", imageMessage.getClass());
        xstream.alias("Image", Image.class);
        return xstream.toXML(imageMessage);
    }

    /**
     * 图文消息对象转换成xml
     *
     * @param newsMessage 图文消息对象
     * @return xml
     */
    public static String newsMessageToXml(NewsMessage newsMessage) {
        xstream.alias("xml", newsMessage.getClass());
        xstream.alias("item", Article.class);
        return xstream.toXML(newsMessage);
    }

    /**
     * 扩展xstream，使其支持CDATA块
     */
    private static XStream xstream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;

                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }

                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

    private WxXmlUtil() {
    }
}

